<template>
  <div class="home-container">
    <el-card class="score-card">
      <template #header>
        <div class="card-header">
          <span>综测加分表</span>
        </div>
      </template>

      <el-form :model="scoreForm" label-width="120px" class="score-form">
        <!-- 学生信息部分 -->
        <el-divider content-position="left">学生信息</el-divider>
        <el-form-item label="姓名">
          <el-input v-model="scoreForm.studentInfo.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="scoreForm.studentInfo.class" placeholder="请输入班级" />
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="scoreForm.studentInfo.studentId" placeholder="请输入学号" />
        </el-form-item>

        <!-- 品德分部分 -->
        <el-divider content-position="left">品德分</el-divider>
        <el-form-item label="初始分">
          <el-input-number v-model="scoreForm.moral.initialScore" :min="-100" :max="100" placeholder="请输入初始分"
            controls="false" />
        </el-form-item>

        <!-- 品德分加分项 -->
        <el-form-item label="加分项">
          <div v-for="(item, index) in scoreForm.moral.addItems" :key="index" class="add-item">
            <el-input v-model="item.name" placeholder="加分项名称" style="width: 200px;" />
            <el-input-number v-model="item.score" :min="-100" :max="100" placeholder="分数" style="width: 150px;" />
            <el-upload v-model:file-list="item.files" :action="`${BASE_URL}/api/upload`" name="file"
              :before-remove="beforeRemove" :on-remove="(file) => handleRemove(file, 'moral', index)"
              :on-preview="handlePreview" :on-exceed="handleExceed" :limit="1" class="upload-demo">
              <el-button size="small" type="primary">上传图片</el-button>
            </el-upload>
            <el-button @click="removeItem('moral', index)" type="danger" size="small">删除</el-button>
          </div>
          <el-button @click="addItem('moral')" type="primary" size="small" style="margin-top: 10px;">添加加分项</el-button>
        </el-form-item>

        <el-form-item label="总分">
          <el-input v-model="scoreForm.moral.totalScore" disabled placeholder="总分" />
        </el-form-item>

        <el-form-item label="转化分">
          <el-input v-model="scoreForm.moral.convertedScore" disabled placeholder="转化分" />
        </el-form-item>

        <!-- 学业分部分 -->
        <el-divider content-position="left">学业分</el-divider>
        <el-form-item label="初始分">
          <el-input-number v-model="scoreForm.academic.initialScore" :min="-100" :max="100" placeholder="请输入初始分"
            controls="false" />
        </el-form-item>

        <!-- 学业分加分项 -->
        <el-form-item label="加分项">
          <div v-for="(item, index) in scoreForm.academic.addItems" :key="index" class="add-item">
            <el-input v-model="item.name" placeholder="加分项名称" style="width: 200px;" />
            <el-input-number v-model="item.score" :min="-100" :max="100" placeholder="分数" style="width: 150px;" />
            <el-upload v-model:file-list="item.files" :action="`${BASE_URL}/api/upload`" name="file"
              :before-remove="beforeRemove" :on-remove="(file) => handleRemove(file, 'academic', index)"
              :on-preview="handlePreview" :on-exceed="handleExceed" :limit="1" class="upload-demo">
              <el-button size="small" type="primary">上传图片</el-button>
            </el-upload>
            <el-button @click="removeItem('academic', index)" type="danger" size="small">删除</el-button>
          </div>
          <el-button @click="addItem('academic')" type="primary" size="small"
            style="margin-top: 10px;">添加加分项</el-button>
        </el-form-item>

        <el-form-item label="总分">
          <el-input v-model="scoreForm.academic.totalScore" disabled placeholder="总分" />
        </el-form-item>

        <el-form-item label="转化分">
          <el-input v-model="scoreForm.academic.convertedScore" disabled placeholder="转化分" />
        </el-form-item>

        <!-- 文体分部分 -->
        <el-divider content-position="left">文体分</el-divider>
        <el-form-item label="初始分">
          <el-input-number v-model="scoreForm.sports.initialScore" :min="-100" :max="100" placeholder="请输入初始分"
            controls="false" />
        </el-form-item>

        <!-- 文体分加分项 -->
        <el-form-item label="加分项">
          <div v-for="(item, index) in scoreForm.sports.addItems" :key="index" class="add-item">
            <el-input v-model="item.name" placeholder="加分项名称" style="width: 200px;" />
            <el-input-number v-model="item.score" :min="-100" :max="100" placeholder="分数" style="width: 150px;" />
            <el-upload v-model:file-list="item.files" :action="`${BASE_URL}/api/upload`" name="file"
              :before-remove="beforeRemove" :on-remove="(file) => handleRemove(file, 'sports', index)"
              :on-preview="handlePreview" :on-exceed="handleExceed" :limit="1" class="upload-demo">
              <el-button size="small" type="primary">上传图片</el-button>
            </el-upload>
            <el-button @click="removeItem('sports', index)" type="danger" size="small">删除</el-button>
          </div>
          <el-button @click="addItem('sports')" type="primary" size="small" style="margin-top: 10px;">添加加分项</el-button>
        </el-form-item>

        <el-form-item label="总分">
          <el-input v-model="scoreForm.sports.totalScore" disabled placeholder="总分" />
        </el-form-item>

        <el-form-item label="转化分">
          <el-input v-model="scoreForm.sports.convertedScore" disabled placeholder="转化分" />
        </el-form-item>

        <!-- 总转化分 -->
        <el-divider content-position="left">总转化分</el-divider>
        <el-form-item label="总转化分">
          <el-input v-model="totalConvertedScore" disabled placeholder="总转化分" />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, computed, watchEffect } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

// 定义后端基础URL
const BASE_URL = 'http://127.0.0.1:5000';

// 转化分系数
const conversionRate = 0.33;

// 使用reactive定义
const scoreForm = reactive({
  studentInfo: {
    name: '',
    class: '',
    studentId: ''
  },
  moral: {
    initialScore: 70,
    addItems: [],
    totalScore: 0,
    convertedScore: 0
  },
  academic: {
    initialScore: 0,
    addItems: [],
    totalScore: 0,
    convertedScore: 0
  },
  sports: {
    initialScore: 70,
    addItems: [],
    totalScore: 0,
    convertedScore: 0
  }
});

// 总转化分
const totalConvertedScore = computed(() => {
  const moralScore = parseFloat(scoreForm.moral.convertedScore) || 0;
  const academicScore = parseFloat(scoreForm.academic.convertedScore) || 0;
  const sportsScore = parseFloat(scoreForm.sports.convertedScore) || 0;
  return (moralScore + academicScore + sportsScore).toFixed(2);
});

// 计算总分和转化分
const calculateTotal = (section) => {
  // 确保section存在且有addItems属性
  if (!scoreForm[section] || !Array.isArray(scoreForm[section].addItems)) {
    return;
  }

  const initialScore = scoreForm[section].initialScore || 0;
  const addItemsTotal = scoreForm[section].addItems.reduce((sum, item) => {
    return sum + (item.score || 0);
  }, 0);

  scoreForm[section].totalScore = initialScore + addItemsTotal;
  scoreForm[section].convertedScore = (scoreForm[section].totalScore * conversionRate).toFixed(2);
};

// 添加加分项  
const addItem = (section) => {
  scoreForm[section].addItems.push({
    name: '',
    score: 0,
    files: []
  });
};

// 删除加分项 
const removeItem = (section, index) => {
  scoreForm[section].addItems.splice(index, 1);
  calculateTotal(section);
};

// 监听初始分变化  
const watchInitialScore = () => {
  // 只监听有addItems的section
  const sections = ['moral', 'academic', 'sports'];
  sections.forEach(section => {
    watchEffect(() => {
      calculateTotal(section);
    });

    watchEffect(() => {
      scoreForm[section].addItems.forEach(item => {
        watchEffect(() => {
          calculateTotal(section);
        });
      });
    });
  });
};

// 处理文件移除  
const handleRemove = (file, section, index) => {
  scoreForm[section].addItems[index].files = scoreForm[section].addItems[index].files.filter(f => f.uid !== file.uid);
};

// 处理文件预览
const handlePreview = (uploadFile) => {
  ElMessage('文件预览功能需要后端支持');
};

// 移除前确认
const beforeRemove = () => {
  return ElMessage('确定要删除该文件吗？');
};

// 处理文件超出限制
const handleExceed = () => {
  ElMessage.error('每个加分项最多只能上传1个文件');
};

// 提交表单
const submitForm = () => {
  // 表单验证
  if (!scoreForm.studentInfo.name || !scoreForm.studentInfo.class || !scoreForm.studentInfo.studentId) {
    ElMessage.error('请填写完整的学生信息');
    return;
  }

  // 检查品德分加分项
  for (let i = 0; i < scoreForm.moral.addItems.length; i++) {
    const item = scoreForm.moral.addItems[i];
    if (!item.name || item.score === null || item.score === undefined) {
      ElMessage.error(`品德分第${i + 1}个加分项信息不完整`);
      return;
    }
  }

  // 检查学业分加分项
  for (let i = 0; i < scoreForm.academic.addItems.length; i++) {
    const item = scoreForm.academic.addItems[i];
    if (!item.name || item.score === null || item.score === undefined) {
      ElMessage.error(`学业分第${i + 1}个加分项信息不完整`);
      return;
    }
  }

  // 检查文体分加分项
  for (let i = 0; i < scoreForm.sports.addItems.length; i++) {
    const item = scoreForm.sports.addItems[i];
    if (!item.name || item.score === null || item.score === undefined) {
      ElMessage.error(`文体分第${i + 1}个加分项信息不完整`);
      return;
    }
  }

  // 如果所有验证通过，使用 axios 提交数据
  axios.post(`${BASE_URL}/api/score`, scoreForm)
    .then(response => {
      ElMessage.success('表单提交成功');
      console.log('服务器响应:', response.data);
    })
    .catch(error => {
      ElMessage.error('提交失败: ' + (error.response?.data?.error || error.message));
      console.error('提交错误:', error);
    });
};

// 重置表单
const resetForm = () => {
  // 重置学生信息
  scoreForm.studentInfo.name = '';
  scoreForm.studentInfo.class = '';
  scoreForm.studentInfo.studentId = '';

  // 重置初始分
  Object.keys(scoreForm).forEach(section => {
    if (section !== 'studentInfo') {
      scoreForm[section].initialScore = section === 'moral' || section === 'sports' ? 70 : 0;
      scoreForm[section].addItems = [];
      scoreForm[section].totalScore = 0;
      scoreForm[section].convertedScore = 0;
    }
  });
  ElMessage('表单已重置');
};

// 初始化监听
watchInitialScore();
</script>

<style lang="less" scoped>
.home-container {
  padding: 20px;
}

.score-card {
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.score-form {
  margin-top: 20px;
}

.add-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
  flex-wrap: wrap;
}

// 响应式调整
@media screen and (max-width: 768px) {
  .add-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .el-input,
  .el-input-number,
  .el-upload {
    width: 100% !important;
    margin-bottom: 10px;
  }
}
</style>
